/**
 * 电机基础信息模块前端功能实现
 */

// API基本路径
let knowledgeBasicAPI_BASE = '/api/feibiao/knowledge/basic';

// 将在DOMContentLoaded中初始化
document.addEventListener('DOMContentLoaded', function() {
    try {
        // 确保全局API_BASE已定义
        if (typeof API_BASE !== 'undefined') {
            knowledgeBasicAPI_BASE = `${API_BASE}/feibiao/knowledge/basic`;
        } else {
            console.warn('全局API_BASE未定义，使用默认API路径');
            knowledgeBasicAPI_BASE = '/api/feibiao/knowledge/basic';
        }

    } catch (err) {
        console.error("电机基础信息模块初始化失败:", err);
    }
});

/**
 * 加载电机基础信息列表
 */
function loadKnowledgeBasicList(page = 0, size = 10) {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求获取数据
    fetch(`${knowledgeBasicAPI_BASE}?page=${page}&size=${size}&sort=motorId,asc`)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    try {
                        const error = JSON.parse(text);
                        throw new Error(`服务器错误 (${response.status}): ${error.message || error.error || response.statusText}`);
                    } catch (e) {
                        if (e instanceof SyntaxError) {
                            throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                        }
                        throw e;
                    }
                });
            }
            return response.json();
        })
        .then(data => {
            renderKnowledgeBasicTable(data);
        })
        .catch(error => {
            console.error('获取电机基础信息数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadKnowledgeBasicList()">重试</button>
                    </div>
                </div>
            `;
            if (typeof showMessage === 'function') {
                showMessage('获取电机基础信息数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 渲染电机基础信息表格
 */
function renderKnowledgeBasicTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机基础信息</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showKnowledgeBasicForm()"></i> 新增</button>
            </div>
        </div>
        
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="knowledgeBasicSearchInput" placeholder="输入关键词搜索...">
                <button class="search-btn" onclick="searchKnowledgeBasic()">搜索</button>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>电机ID</th>
                        <th>电机型号</th>
                        <th>生产厂商</th>
                        <th>额定功率(kW)</th>
                        <th>额定电压(V)</th>
                        <th>额定电流(A)</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.motorId || ''}</td>
                    <td>${item.motorType || ''}</td>
                    <td>${item.manufacturer || ''}</td>
                    <td>${item.ratedPower !== undefined ? item.ratedPower.toFixed(2) : ''}</td>
                    <td>${item.ratedVoltage !== undefined ? item.ratedVoltage.toFixed(2) : ''}</td>
                    <td>${item.ratedCurrent !== undefined ? item.ratedCurrent.toFixed(2) : ''}</td>
                    <td>${formatDateTime(item.infoUpdateTime) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewKnowledgeBasic('${item.motorId}')">查看</a>
                        <a href="javascript:void(0)" onclick="editKnowledgeBasic('${item.motorId}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteKnowledgeBasic('${item.motorId}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    // 添加分页控件 - 改为与failure.js一致的分页样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadKnowledgeBasicList(' + (data.number - 1) + ', ' + data.size + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadKnowledgeBasicList(${i}, ${data.size})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadKnowledgeBasicList(' + (data.number + 1) + ', ' + data.size + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 搜索电机基础信息
 */
function searchKnowledgeBasic() {
    const keyword = document.getElementById('knowledgeBasicSearchInput').value.trim();
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据搜索中...</div>';
    
    // 发起请求，添加排序参数
    fetch(`${knowledgeBasicAPI_BASE}/search?keyword=${encodeURIComponent(keyword)}&sort=motorId,asc`)
        .then(response => {
            if (!response.ok) {
                throw new Error('搜索请求失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            renderKnowledgeBasicTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('搜索失败: ' + error.message, 'error');
            }
            loadKnowledgeBasicList(); // 失败时加载所有数据
        });
}

/**
 * 显示电机基础信息表单(新增/编辑)
 */
function showKnowledgeBasicForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    
    // 构建表单HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机基础信息</h2>
            <button class="btn btn-default" onclick="loadKnowledgeBasicList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
        
        <form id="knowledgeBasicForm" class="data-form" onsubmit="submitKnowledgeBasicForm(event)">
            <div class="form-group">
                <label for="motorId">电机ID <span class="required">*</span></label>
                <input type="text" id="motorId" name="motorId" class="form-control" value="${isEdit ? data.motorId : ''}" ${isEdit ? 'readonly' : ''} placeholder="如：M001" required>
                <small class="form-text">电机唯一标识，如M001</small>
            </div>
            
            <div class="form-group">
                <label for="motorType">电机型号 <span class="required">*</span></label>
                <input type="text" id="motorType" name="motorType" class="form-control" value="${isEdit ? data.motorType : ''}" placeholder="如：48V BSG电机" required>
                <small class="form-text">电机型号，如48V BSG电机</small>
            </div>
            
            <div class="form-group">
                <label for="manufacturer">生产厂商 <span class="required">*</span></label>
                <input type="text" id="manufacturer" name="manufacturer" class="form-control" value="${isEdit ? data.manufacturer : ''}" placeholder="如：XX电机制造有限公司" required>
                <small class="form-text">生产厂商全称</small>
            </div>
            
            <div class="form-group">
                <label for="ratedPower">额定功率(kW) <span class="required">*</span></label>
                <input type="number" id="ratedPower" name="ratedPower" class="form-control" value="${isEdit && data.ratedPower !== undefined ? data.ratedPower : ''}" step="0.01" min="0" placeholder="如：75.00" required>
                <small class="form-text">额定功率，单位：kW</small>
            </div>
            
            <div class="form-group">
                <label for="ratedVoltage">额定电压(V) <span class="required">*</span></label>
                <input type="number" id="ratedVoltage" name="ratedVoltage" class="form-control" value="${isEdit && data.ratedVoltage !== undefined ? data.ratedVoltage : ''}" step="0.01" min="0" placeholder="如：220.00" required>
                <small class="form-text">额定电压，单位：V</small>
            </div>
            
            <div class="form-group">
                <label for="ratedCurrent">额定电流(A) <span class="required">*</span></label>
                <input type="number" id="ratedCurrent" name="ratedCurrent" class="form-control" value="${isEdit && data.ratedCurrent !== undefined ? data.ratedCurrent : ''}" step="0.01" min="0" placeholder="如：10.00" required>
                <small class="form-text">额定电流，单位：A</small>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadKnowledgeBasicList()">取消</button>
            </div>
        </form>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 提交电机基础信息表单
 */
function submitKnowledgeBasicForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const form = document.getElementById('knowledgeBasicForm');
    const formData = new FormData(form);
    const data = {};
    
    // 转换表单数据为JSON对象
    formData.forEach((value, key) => {
        // 转换数字类型
        if (key === 'ratedPower' || key === 'ratedVoltage' || key === 'ratedCurrent') {
            data[key] = parseFloat(value);
        } else {
            data[key] = value;
        }
    });
    
    // ID是否为只读状态判断是新增还是编辑
    const isEdit = document.getElementById('motorId').readOnly;
    const motorId = data.motorId;
    
    // 发起请求
    fetch(`${knowledgeBasicAPI_BASE}${isEdit ? '/' + motorId : ''}`, {
        method: isEdit ? 'PUT' : 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        }
        return response.json();
    })
    .then(result => {
        if (typeof showMessage === 'function') {
            showMessage(`电机基础信息${isEdit ? '更新' : '添加'}成功!`, 'success');
        }
        loadKnowledgeBasicList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        if (typeof showMessage === 'function') {
            showMessage('保存失败: ' + error.message, 'error');
        }
    });
}

/**
 * 查看电机基础信息详情
 */
function viewKnowledgeBasic(motorId) {
    // 发起请求获取详情
    fetch(`${knowledgeBasicAPI_BASE}/${motorId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取详情失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeBasicDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 显示电机基础信息详情
 */
function showKnowledgeBasicDetail(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建详情HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机基础信息详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeBasicList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="data-detail">
            <div class="detail-group">
                <label>电机ID:</label>
                <div>${data.motorId || '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>电机型号:</label>
                <div>${data.motorType || '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>生产厂商:</label>
                <div>${data.manufacturer || '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>额定功率:</label>
                <div>${data.ratedPower !== undefined ? data.ratedPower.toFixed(2) + ' kW' : '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>额定电压:</label>
                <div>${data.ratedVoltage !== undefined ? data.ratedVoltage.toFixed(2) + ' V' : '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>额定电流:</label>
                <div>${data.ratedCurrent !== undefined ? data.ratedCurrent.toFixed(2) + ' A' : '--'}</div>
            </div>
            
            <div class="detail-group">
                <label>信息更新时间:</label>
                <div>${formatDateTime(data.infoUpdateTime) || '--'}</div>
            </div>
            
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editKnowledgeBasic('${data.motorId}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteKnowledgeBasic('${data.motorId}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadKnowledgeBasicList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 编辑电机基础信息
 */
function editKnowledgeBasic(motorId) {
    // 发起请求获取详情
    fetch(`${knowledgeBasicAPI_BASE}/${motorId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取详情失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeBasicForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 删除电机基础信息
 */
function deleteKnowledgeBasic(motorId) {
    if (!confirm(`确定要删除电机ID为 ${motorId} 的记录吗？此操作不可恢复!`)) {
        return;
    }
    
    // 发起删除请求
    fetch(`${knowledgeBasicAPI_BASE}/${motorId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '删除失败');
                } catch (e) {
                    throw new Error(text || '删除失败');
                }
            });
        }
        
        if (typeof showMessage === 'function') {
            showMessage('删除成功!', 'success');
        }
        loadKnowledgeBasicList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        if (typeof showMessage === 'function') {
            showMessage('删除失败: ' + error.message, 'error');
        }
    });
}

/**
 * 格式化日期时间
 */
function formatDateTime(datetime) {
    if (!datetime) return '';
    
    let date;
    if (typeof datetime === 'string') {
        date = new Date(datetime);
    } else if (datetime instanceof Object && datetime.time) {
        date = new Date(datetime.time);
    } else {
        date = new Date(datetime);
    }
    
    if (isNaN(date.getTime())) return datetime.toString();
    
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
} 